//
//  LoginMVVMViewController.swift
//  test-ios
//
//  Created by wyz5204 on 2023/5/27.
//

import UIKit
import RxCocoa
import RxSwift
import SwiftyRSA

import CocoaLumberjack
import SwiftyJSON

class LoginMVVMViewController: SimpleViewController<LoginViewModel> {
    
    private lazy var containerView : UIView = {
        return UIView()
    }()
    
    private lazy var loginTipView : UILoginTipView = {
        return UILoginTipView()
    }()
    
    private lazy var phoneInputView : UIPhoneInputView = {
        return UIPhoneInputView()
    }()
    
    private lazy var codeInputView : UICodeInputView = {
        return UICodeInputView()
    }()
    
    private lazy var loginBt : UIButton = {
        return UIButton().then { view in
            view.setTitle("验证码登录", for: .normal)
            view.backgroundColor = UIColor.blue
            view.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        }
    }()
    
    private lazy var changeUrl = {
        return UIButton().then { view in
            view.setTitleAndColor("切换环境")
        }
    }()
    
    private lazy var privacyBtView = {
        return UIButton(type: .custom).then { view in
            view.setImage(UIImage(named: "login_agree_select"), for: .normal)
            view.setImage(UIImage(named: "login_agree_selected"), for: .selected)
            /// 扩大按钮点击事件
            view.hitEdgeInsets = UIEdgeInsets.init(top: -20, left: -20, bottom: -20, right: -20)
        }
    }()
    
    override func initView(_ contentView: UIView) {
        view.backgroundColor = .white
        // 容器框
        containerView.addTo(self.view){ view  in
            //view.backgroundColor = .red
            view.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(24)
                make.right.equalToSuperview().offset(-24)
                make.top.equalToSuperview().offset(86)
                make.bottom.equalToSuperview().offset(-40)
            }
        }
        // login 登陆介绍
        loginTipView.addTo(containerView) { view in
            view.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.left.right.equalToSuperview()
                make.height.equalTo(100)
            }
        }
        
        // 手机号输入框
        phoneInputView.addTo(containerView) { view in
            view.snp.makeConstraints { make in
                make.top.equalTo(loginTipView.snp.bottom).offset(36)
                make.left.right.equalToSuperview()
                make.height.equalTo(40)
            }
        }
        
        // 验证码输入框
        codeInputView.addTo(containerView) { view in
            view.snp.makeConstraints { (make) in
                make.top.equalTo(phoneInputView.snp.bottom).offset(10)
                make.left.right.equalToSuperview()
                make.height.equalTo(65)
            }
        }
        // 隐私协议的按钮
        privacyBtView.addTo(containerView) { view, parent in
            view.snp.makeConstraints { make in
                make.top.equalTo(codeInputView.snp.bottom).offset(20)
                make.left.equalToSuperview()
                make.height.equalTo(30)
            }
        }
        
        // 登陆按钮
        loginBt.addTo(containerView) { view in
            view.snp.makeConstraints { make in
                make.top.equalTo(codeInputView.snp.bottom).offset(75)
                make.left.right.equalToSuperview()
                make.height.equalTo(44)
            }
        }
        
        // 切换环境的按钮
        changeUrl.addTo(containerView) { view in
            view.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview()
            }
        }
    }
    
    override func bindViewModel(_ viewModel: LoginViewModel) {
        
        // 普通的环境切换点击事件
        changeUrl.rx.tap.subscribe { [weak self ] event in
            DDLogDebug(" 点击了 切换环境  \(event)")
            let alert = UIAlertController.init(title: "切换环境", message: " qiehun ", preferredStyle: .actionSheet)
            
            alert.addAction(UIAlertAction.init(title:"打开主页", style: .default, handler: { (action) in
                self?.viewModel?.postMessage(RDNotification.login)
            }))
            
            alert.addAction(UIAlertAction.init(title:"获取RSA", style: .default, handler: { (action) in
                self?.viewModel?.getrsa()
            }))
            
            alert.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { action in DDLogDebug(" 点击了 cancel  \(action)")
            }))
            self?.present(alert, animated: true, completion: nil)
            
        }.disposed(by: rx.disposeBag)
        
        //登陆点击事件
        loginBt.rx.tap.asDriver().drive (onNext : {[weak self] in
            guard let this = self else {
                return
            }
            this.login(this.phoneInputView.textField.text! , this.codeInputView.codeField.text!)
        }).disposed(by: rx.disposeBag)
        
        //隐私协议事件
        let privacyDriverBool =  privacyBtView.rx.tap.map { [weak self]  unit -> Bool in
            self?.privacyBtView.isSelected.toggle()
            return self?.privacyBtView.isSelected ?? false
        }.asDriver(onErrorJustReturn: false)
        
        let output = viewModel.transform(LoginViewModel.Input(
            // 手机号码输入框的
            phoneDriverString: phoneInputView.textField.rx.text.orEmpty.asDriver(),
            // 验证码
            codeDriverString: codeInputView.codeField.rx.text.orEmpty.asDriver(),
            // 隐私协议点击与否
            privacyDriverBool: privacyDriverBool
        ))
        
        // 按钮可点击与否
        output.loginBtEnabledDriverBool.drive(onNext: { [weak self] isEnable in
            print(" loginBtEnabledDriverBool \(isEnable)")
            self?.loginBt.isEnabled = isEnable
        }).disposed(by: rx.disposeBag)
        
    }
    
    
    func login(_ phone : String ,_ code : String){
        print(">>>> login \(phone) -- \(code)" )
        viewModel?.login(phone, code)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        let standard = UserDefaults.standard
        if(standard.string(forKey: "crmId")?.count ?? 0 > 0 && standard.string(forKey: "token")?.count ?? 0 > 0){
            self.viewModel?.postMessage(RDNotification.login)
        }
    }
}

class LoginViewModel : SimpleViewModel , MVVMTransform{
    
    struct Input {
        let phoneDriverString : Driver<String>
        let codeDriverString : Driver<String>
        let privacyDriverBool : Driver<Bool>
    }
    
    struct Output {
        let loginBtEnabledDriverBool : Driver<Bool>
    }
    
    
    func transform(_ input: Input) -> Output {
        input.privacyDriverBool.drive(onNext: { isSelect in
            print("privacyDriverBool isSelect \(isSelect)")
        }).disposed(by: rx.disposeBag)
        
        let isLoginBtEnable = Driver.combineLatest(input.phoneDriverString, input.codeDriverString, input.privacyDriverBool) { phoneString, codeString, privacyBool in
            return phoneString.count >= 0 && codeString.count >= 0 && privacyBool
        }.distinctUntilChanged()
        
        return Output(loginBtEnabledDriverBool : isLoginBtEnable )
    }
    
    let netModel = RDNetModel.shared
    
    func login(_ username : String , _ password : String){
        netModel.loginObj(phone: username, code: password).subscribe { [weak self ]json in
            print(">>>> login onSuccess \(json)")
            // 初始化各种参数
            let standard = UserDefaults.standard
            standard.set(json.data?.token, forKey: "token")
            standard.set(json.data?.userInfo.crmID, forKey: "crmId")
            standard.synchronize()
            // 初始化数据库文件，使用crmid作为数据库名称
            
            self?.postMessage(RDNotification.login)
            
        } onFailure: { error in
            print(">>>> login onFailure \(error)")
        }.disposed(by: rx.disposeBag)
    }
    
    func getrsa(){
        netModel.getRSAKey().subscribe { json in
            print(">>>> getrsa onSuccess \(type(of: json)) \(json)")
            guard let stringKey = json["data"].rawString() else {
                return
            }
            do {
                let publicKey = try PublicKey(pemEncoded: stringKey)
                print(" RSA Public Key" , publicKey)
                let str = "a123456"
                let clear = try ClearMessage(string: str, using: .utf8)
                let encrypted = try clear.encrypted(with: publicKey, padding: .PKCS1)
                
                let data = encrypted.data
                print(data)
                
                let base64String = encrypted.base64String
                print(base64String)
                
            } catch {
                print(">> \(error)")
            }
        } onFailure: { error in
            print(">>>> login onFailure \(type(of: error)) \(error)")
        } .disposed(by: rx.disposeBag)
    }
    
    func getAppItems(){
       
    }
}
